import React from 'react'
import {HashRouter, Route, BrowserRouter, Switch, Link, Redirect, withRouter} from 'react-router-dom'

const fakeAuth = {
    isAuthenticated: false,
    authenticate(cb) {
        this.isAuthenticated = true
        setTimeout(cb, 1000) // 模拟异步。
    },
    signout(cb) {
        this.isAuthenticated = false
        setTimeout(cb, 1000)
    }
}

const AuthPage = withRouter(({history}) => {
    return fakeAuth.isAuthenticated ? (<p>Welcome!
        <button onClick={()=>{fakeAuth.signout(()=>history.push('/'))}}>Signout</button>
    </p>) : (<p>You're not Logined!</p>)
})

const PrivateRoute = ({component: Component, ...rest}) => {
    console.log(rest);
    // Object {path: "/protected"}
    return (
        <Route {...rest} render={props => (
      fakeAuth.isAuthenticated ? (
        <Component {...props}/>
      ) : (
        <Redirect to={{
          pathname: '/login',
          state: { from: props.location }
        }}/>
      )
    )}/>
    )
}

const Public = () => {
    return (<h3>公开的页面</h3>)
}
const Private = () => <h3>非公开的页面</h3>

class Login extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            redirectToReferrer: false
        }
        this.login = ()=> {
            fakeAuth.authenticate(() => {
                this.setState({redirectToReferrer: true})
            })
        }
    }

    render() {
        const {from} = this.props.location.state || {from: {pathname: '/'}}
        const {redirectToReferrer} = this.state

        if (redirectToReferrer) {
            return (
                <Redirect to={from}/>
            )
        }

        return (
            <div>
                <p>若想访问 {from.pathname} ，你需要先登录</p>
                <button onClick={this.login}>登录</button>
            </div>
        )
    }
}

const Auth = ()=> {
    return (<BrowserRouter>
        <div>
            <AuthPage />
            <ul>
                <li><Link to="/public">public page</Link></li>
                <li><Link to="/protected">protected page</Link></li>
            </ul>
            <Route path="/public" component={Public}/>
            <Route path="/login" component={Login}/>
            <PrivateRoute path="/protected" age="12" component={Private}/>
        </div>
    </BrowserRouter>)
}

export default Auth

